package com.tang.model.template.jdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/8/22 22:01
 * @Desc 不应该是懒汉式，应该是饿汉式
 * @Remarks
 */
public class ConnectionPool {
    public static final int SIZE = 3;
    //    享元模式保存的数据 Connection
    private static Vector<Connection> connections;

    private static volatile ConnectionPool connectionPool = new ConnectionPool();

    public static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "hadoop";

    private ConnectionPool() {
        connections = new Vector<Connection>(SIZE);
        initConnection();
    }

    private static void initConnection() {
        try {
            Class<?> clazz = Class.forName(DRIVER_NAME);
            for (int i = 0; i < SIZE; i++) {
                Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                connections.add(connection);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static Connection getConnection() {
        if (connections.size() > 0) {
            return connections.remove(0);
        }
        return null;
    }

    public static void release(Connection connection) {
        if (null == connectionPool) {
            throw new RuntimeException("尚未创建连接，不能归还连接对象！");
        }
        connections.add(connection);
    }

}
